/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim</a>, 2004
 */
package hk.com.carfield.action.process;

import hk.com.carfield.core.Context;
import hk.com.carfield.util.StringUtil;
import hk.com.carfield.web.Request;
import java.io.File;
import java.io.IOException;

public final class New implements Process {
	private static final String filename = "filename";
	public File process(Context c, Request req, File l) throws IOException {
		//TODO add validation
		final String name = req.getParameter(filename);
		if (StringUtil.notBlank(name)) {
			//TODO difference file type should be process individaully, as this not valid for image, and not meaningful for text either
			final File location = l.isDirectory()?l:l.getParentFile();
			final File newFile = new File(location, name);
			final boolean isDirectory = name.endsWith("/") ? true : false;
			final boolean success = isDirectory ? newFile.mkdirs() : newFile.createNewFile();
			if(success)
				return newFile.getParentFile();
			else if(newFile.exists())
				throw new IOException("File already exist");
			else
				throw new IOException("Cannot create new file");
		}
		return l.getParentFile();
	}
	public String actionCode(){
		return "new";
	}
	public boolean adminOnly() {
		return true;
	}
}